package com.shiro;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.shiro.config.Ini;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.config.IniFilterChainResolverFactory;
import com.pojo.UrlFilter;
import com.service.IUrlFilterService;

public class ShiroPermissionFactory extends ShiroFilterFactoryBean {

	@Resource
	private IUrlFilterService urlFilterService;

	/** 记录配置中的过滤链 */
	public static String definition = "";

	/**
	 * 初始化设置过滤链
	 */
	@Override
	public void setFilterChainDefinitions(String definitions) {
		definition = definitions;// 记录配置的静态过滤链
		List<UrlFilter> urlFilters = urlFilterService.getUrlFilters();
		Map<String, String> otherChains = new HashMap<String, String>();
		urlFilters.forEach(urlFilter -> {
			otherChains.put(urlFilter.getUrl(), urlFilter.getValue());
		});
		//访问该项目的用户是身份验证通过或RememberMe登录的都可以
		otherChains.put("/**", "user");
		// 加载配置默认的过滤链
		Ini ini = new Ini();
		ini.load(definitions);
		Ini.Section section = ini.getSection(IniFilterChainResolverFactory.URLS);
		if (CollectionUtils.isEmpty(section)) {
			section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		}
		// 加上数据库中过滤链
		section.putAll(otherChains);
		setFilterChainDefinitionMap(section);
	}

}